//
//  SWWebTools.swift
//  weibo1
//
//  Created by 李进 on 15/10/16.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit
import AFNetworking

//定义枚举
enum sendMedoth: String{
    
    case GET = "GET"
    case POST = "POST"
}

class SWWebTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    //1994640257
    
    //d333d669f2ebadf69f0f2369a8724753
    
    private let appKey = "1512280451"
    private let appSecret = "c44685408280c144855a1b3a6c1c9bf7"
    private let redirectUrl = "http://www.baidu.com"
    
    typealias RequestCallBack = (result: AnyObject?, error: NSError?)->()

    
    //创建单例方法,单例方式是通过懒加载来实现的
        static let shareWebTools: SWWebTools = {
            
            let tool = SWWebTools(baseURL: nil)
            
            //设置反序列化
            tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
            
            return tool
        }()
}

// MARK: - 用户信息方法
extension SWWebTools {
    
    func loaduserInfo (uid: String, finished: RequestCallBack){
        
        let urlstr = "https://api.weibo.com/2/users/show.json"
        
        var params = [String : AnyObject]()
        
        params["uid"] = uid
        
        //"access_token": accessToken]
        
        tokenRequest(.GET, URLString: urlstr, parameters: params, finished: finished)
        
        // request(.GET, URLsrting: urlstr, parameter: params, finisesh: finished)
        
    }
}


// MARK: - OAuth 相关方法
extension SWWebTools {
    
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        //print(urlString)
        
        return NSURL(string: urlString)!
    }
    
    /// - 验证令牌参数
    var token:[String:AnyObject]? {
        
        //先判断token是否有效
        if let TK = userAccViewModel.shareAccViewModel.accessToken{
            return ["access_token": TK]
        }
        
        return nil
        
    }
    
    
    
    /// 加载微博关注的微博信息
    ///
    /// - parameter uid:         uid
    /// - parameter accessToken: 令牌
    /// - parameter finished:    成功回调
    func loadUserFriend(since_id: Int,max_id: Int,finished: RequestCallBack){
        
//        guard var params = token else{
//            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
//            
//            return
//        }
        
        var params = [String: AnyObject]()
        
        if since_id > 0 {
            params["since_id"] = since_id
        }else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
        //request(.GET, URLsrting: urlString, parameter: params, finisesh: finished)
    }
    
    
    
    /// 加载 AccessToken
    func loadAccessToken(code: String, finished: RequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(sendMedoth.POST, URLsrting: urlString, parameter: params, finisesh: finished)
    }
}





// MARK: - 发送微博，网络请求
extension SWWebTools{
    
    /// token 请求抽取
    ///
    /// - parameter sendmedoth: 请求方式
    /// - parameter URLString:  url base
    /// - parameter parameters: 传递的参数
    /// - parameter finished:   完成请求的回调
    private func tokenRequest(sendmedoth: sendMedoth, URLString: String, var parameters: [String: AnyObject]?, finished: RequestCallBack){
        
        guard let token = userAccViewModel.shareAccViewModel.accessToken else{
            // token 无效
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        
        if  parameters == nil {
            
            parameters = [String: AnyObject]()
            
        }
        parameters!["access_token"] = token
        
        // 2. 发起网络请求
        request(sendmedoth, URLsrting: URLString, parameter: parameters, finisesh: finished)
        
    }
    
    // MARK: -测试上传多张图片
//    class func uploadImages(images:[UIImage],var parameters:[String : AnyObject]?,finished:RequestCallBack){
//        
//        //还需要判断，token是否有效
//        guard let token = userAccViewModel.shareAccViewModel.accessToken  else{
//            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
//            return
//        }
//        
//        let urlString = "https://api.weibo.com/2/statuses/update.json"
//        if  parameters == nil {
//            parameters = [String : AnyObject]()
//        }
//        
//        if images.count == 0{
//            print("没有值")
//            return
//        }
//        parameters!["access_token"] = token
//        
//        
//        
//        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
//            //便利图片数组
//            for  a in 0..<images.count{
//                let image = images[a]
//                var imagedata:NSData?
//                    imagedata = UIImagePNGRepresentation(image)
//                formdata.appendPartWithFileData(imagedata)
//            }
//            }, success: { (_, result) -> Void in
//                finished(result: result, error: _)
//            }) { (_, error) -> Void in
//                finished(result: _, error: error)
//        }
//    }
//    
    
    

    
    /// 发送文字微博的网络方法
    ///
    /// - parameter status:   需要上传的文字信息
    /// - parameter finished: 完成网络方法的回调
    func sendNewMessage(status: String, image: UIImage?,finished: RequestCallBack){
        
//        guard var params = token else{
//            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
//            
//            return
//        }
        
        var params = [String: AnyObject]()
        
         params["status"] = status
        
        if image == nil {
            
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
            
        }else {
            
            let data = UIImagePNGRepresentation(image!)
            let urlstring = "https://upload.api.weibo.com/2/statuses/upload.json"
           
            upLoadData(urlstring, data: data!, name: "pic", parameters: params, finished: finished)
        }
        
    }
    
    /// 上传文件方法
    ///
    /// - parameter URLString:  url
    /// - parameter data:       文件二进制数据
    /// - parameter name:       在服务器上的名字
    /// - parameter parameters: 传递的参数
    /// - parameter finished:   完成回调
    private func upLoadData(URLString: String, data: NSData ,name: String, var parameters: [String : AnyObject]? , finished: RequestCallBack){
        
        
        //还需要判断，token是否有效
        guard let token = userAccViewModel.shareAccViewModel.accessToken  else{
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        
        
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        
        //parameters!["pic"] = data
        parameters!["access_token"] = token
         
        
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
            
            formdata.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            //print("漂亮\(formdata)")
            
            }, success: { (_, result) -> Void in
                print("漂亮 ＋ good\(result)")
                finished(result: result, error: nil)
                
                
            }) { (_, error) -> Void in
                print("好玩了\(error)")
                finished(result: nil, error: error)
        }
    }
    
    
    
}

//MARK:封装网络方法
extension SWWebTools{
    
    func request(sendmedoth:sendMedoth ,URLsrting: String , parameter: [String:AnyObject]? ,finisesh:RequestCallBack){
        
        //定义成功回调
        let succes = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            
            //print(result)
            finisesh(result: result, error: nil)
            
        }
        
        //定义失败回调
        let feail = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            
            print("+++++++++++++++++++++++++++++\(error)")
            finisesh(result: nil, error: error)
            
        }
        
        if sendmedoth == sendMedoth.GET {
            
            GET(URLsrting, parameters: parameter, success: succes, failure: feail)
            
        }else{
            POST(URLsrting, parameters: parameter, success: succes, failure: feail)
        }
    }
}